package com.atguigu.gmall.cart.service.impl;

import com.atguigu.gmall.cart.mapper.CarInfoMapper;
import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;

/**
 * @author luhan
 * @create 2022/5/22 11:02
 */
@Service
public class CartInfoServiceInpl implements CartInfoService {

    @Autowired
    private CarInfoMapper carInfoMapper;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addToCart(Long skuId, String userId, Integer skuNum) {
        /*
            添加购物车逻辑
            1.判断购物车是否有该商品
                true：数量相加
                false：insert
         */
        // select * from cart_info where sku_id = ? and user_id = ?
        QueryWrapper<CartInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sku_id",skuId);
        queryWrapper.eq("user_id",userId);
        CartInfo cartInfoExist = carInfoMapper.selectOne(queryWrapper);
        if (cartInfoExist!=null){
            // 数据相加
            cartInfoExist.setSkuNum(cartInfoExist.getSkuNum()+skuNum);
            // 赋值商品实时价格
            BigDecimal skuPrice = productFeignClient.getSkuPrice(skuId);
            cartInfoExist.setSkuPrice(skuPrice);
            carInfoMapper.updateById(cartInfoExist);

            // 添加的时候直接添加到缓存

        } else {
            // insert
            CartInfo cartInfo = new CartInfo();
            cartInfo.setSkuId(skuId);
            cartInfo.setUserId(userId);
            cartInfo.setSkuNum(skuNum);
            SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
            cartInfo.setCartPrice(skuInfo.getPrice());
            cartInfo.setImgUrl(skuInfo.getSkuDefaultImg());
            cartInfo.setSkuName(skuInfo.getSkuName());
            cartInfo.setCreateTime(new Timestamp(new Date().getTime()));
            cartInfo.setUpdateTime(new Timestamp(new Date().getTime()));

            carInfoMapper.insert(cartInfo);

            // 添加的时候直接添加到缓存
        }
    }
}
